package com.lwei.ljpro.controller;

import com.lwei.ljpro.dto.ExcelData;
import com.lwei.ljpro.dto.Message;
import com.lwei.ljpro.emun.ProcessResult;
import com.lwei.ljpro.entry.UserEntry;
import com.lwei.ljpro.entry.WorkingEntry;
import com.lwei.ljpro.service.IUserService;
import com.lwei.ljpro.service.IWorkingService;
import com.lwei.ljpro.util.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/adminRest")
public class AdminRestController {

    private Logger logger = LoggerFactory.getLogger("adminRest");
    @Autowired
    IWorkingService workingService;

    @Autowired
    IUserService userService;

    @RequestMapping("/list")
    public Message<WorkingEntry> listCustomerWork(WorkingEntry entry, @Param("query") String query,
                                                  @Param("planTimeHorizon") String planTimeHorizon, @Param("doneTimeHorizon") String doneTimeHorizon){
        List<WorkingEntry> workingEntryList;
        if(StringUtils.isNotBlank(query)){
            workingEntryList = workingService.listWorkingByPlanTime(planTimeHorizon, doneTimeHorizon, entry.getUserId());
        }else{
            workingEntryList = workingService.listWorkingAll();
        }

        Message<WorkingEntry> message = new Message<>(ProcessResult.SUCCESS, "用户工作计划列表", workingEntryList);
        message.setQueryDto(entry);
        return message;
    }

    /**
     * 获取当前用户列表
     * @return 用户
     */
    @RequestMapping("/listUser")
    public Message<UserEntry> listUser(){

        List<UserEntry> userEntries = userService.listUserAll();
        return new Message<>(ProcessResult.SUCCESS, "用户表",userEntries);
    }

    @RequestMapping("/check")
    public Message checkWorkDone(Long id, boolean done){
        WorkingEntry workingEntry = workingService.getWorkingEntryById(id);
        workingEntry.setDone(done);

        WorkingEntry entry = workingService.updateWorkingEntry(workingEntry);
        if(entry != null){
            return Message.instance(ProcessResult.SUCCESS);
        } else {
            return Message.instance(ProcessResult.FAIL);
        }
    }

    /**
     * 管理员提交表单保存
     * @param workingEntry 表单对象
     * @return 结果
     */
    @RequestMapping("/save")
    public Message saveCustomerWork(WorkingEntry workingEntry, UserEntry userEntry, HttpServletResponse response){
        Boolean result = workingService.saveWorkingEntryWithUser(workingEntry, userEntry);

        if(result){
            return Message.instance(ProcessResult.SUCCESS);
        } else{
            return Message.instance(ProcessResult.FAIL);
        }
    }

    @RequestMapping("/edit")
    public Message editCustomerWork(WorkingEntry entry){

        WorkingEntry workingEntry = workingService.updateWorkingEntry(entry);

        if(workingEntry != null){
            return Message.instance(ProcessResult.SUCCESS);
        } else{
            return Message.instance(ProcessResult.FAIL);
        }
    }

    @RequestMapping("/delete")
    public Message deleteCustomerWork(Long id){

        Boolean isDelete = workingService.deleteWorkingEntryById(id);
        if(isDelete){
            return Message.instance(ProcessResult.SUCCESS);
        } else{
            return Message.instance(ProcessResult.FAIL);
        }
    }

    /**
     * 导出excel
     * @param entry 实体 查询条件userID
     * @param query 查询方式标识
     * @param response re
     * @param planTimeHorizon 查询条件 计划时间返回
     * @param doneTimeHorizon 查询条件 完成时间范围
     */
    @RequestMapping("/exportExcel")
    public void exportExcel(WorkingEntry entry, @Param("export") String query, HttpServletResponse response,
                            @Param("planTimeHorizon") String planTimeHorizon, @Param("doneTimeHorizon") String doneTimeHorizon){

        List<WorkingEntry> workingEntryList;
        if("export".equals(query)){
            workingEntryList = workingService.listWorkingByPlanTime(planTimeHorizon, doneTimeHorizon, entry.getUserId());
        } else{
            String[] idStrs = query.split(",");
            List<String> idStr = Arrays.asList(idStrs);
            List<Long> ids = new ArrayList<>();
            idStr.forEach(id -> ids.add(Long.valueOf(id)));
            workingEntryList = workingService.listWorkingByIds(ids);
        }

        List<ExcelData> dataList = workingService.workingList2ExcelData(workingEntryList);

        try {

            if(dataList.size() > 0){
                ExcelUtils.exportExcel(response, "导出列表", dataList);
            } else{
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("<script type='text/javascript'>alert(\"导出数据为空\");</script>");
                response.getWriter().write("<script type='text/javascript'>history.back(-1);</script>");
            }
        } catch (Exception e) {
            logger.error("导出Excel出错", e);
        }
    }


}
